<?php

namespace Yolo\Observers;

use Yolo\Di\Annotations\Singleton;
use Yolo\Utils\Console;

#[Singleton]
class ObserverManager
{
    /**
     * @var ObserverInterface[] $observers The observers to notify.
     */
    protected array $observers = [];

    public function subscribe(ObserverInterface $observer): void
    {
        if (in_array($observer, $this->observers)) {
            return;
        }

        $this->observers[] = $observer;

        Console::log("Observer: " . get_class($observer) . ' subscribed.');
    }

    public function unsubscribe(ObserverInterface $observer): void
    {
        $key = array_search($observer, $this->observers);

        if ($key !== false) {

            unset($this->observers[$key]);
        }
    }

    public function notify(string $event, array $data = []): void
    {
        foreach ($this->observers as $observer) {

            if (in_array($event, $observer->listens())) {

                $observer->process($event, $data);
            }
        }
    }
}
